package per.wxp.kafka.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import per.wxp.kafka.entity.Message;
import per.wxp.kafka.util.Constant;

import javax.annotation.Resource;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class FileReadService {


    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private KafkaService kafkaService;


    /**
     * 读取文件的方法
     * @param path 文件路径
     * **/
    public  void randomRed(String path ){
        try{
            File file = new File(path);
            if(file == null){
                logger.info("文件不存在");
                return;
            }
            RandomAccessFile raf=new RandomAccessFile(file, "r");
            //获取RandomAccessFile对象文件指针的位置，初始位置是0
            logger.info("RandomAccessFile文件指针的初始位置:"+raf.getFilePointer());
            raf.seek(Constant.pointer);//移动文件指针位置
            String line =null;
            //循环读取
            while((line = raf.readLine())!=null){
                if(line.equals("")){
                    continue;
                }
                //打印读取的内容,并将字节转为字符串输入，做转码处理
                line = new String(line.getBytes("ISO-8859-1"),"utf-8");
                logger.info("line :"+line);
                Message m=new Message();
                m.setId(Constant.pointer);
                m.setDetails(line);
                kafkaService.sendKafka("test",m);
            }
            //文件读取完毕后，将文件指针游标设置为当前指针位置
            Constant.pointer = raf.getFilePointer();

        }catch(Exception e){
            logger.error("异常："+ e.getMessage());
            e.printStackTrace();
        }
    }

    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");

    public  void writeLogs(File logFile,String msgInfo)throws IOException {
        if(!logFile.exists()) {
            logFile.createNewFile();
        }
        Writer txtWriter = new FileWriter(logFile,true);
        txtWriter.write(dateFormat.format(new Date()) + "\t" + msgInfo + "\n");
        txtWriter.flush();
        txtWriter.close();
    }





}
